package lomasky.ma.httpUtils;




import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * User: Eicky
 * Date: 2015-12-08
 * Content:
 */
public class JsonUtil {

    public static <T> T getObject(String jsonStr, Class<T> cls) {
        Gson gson = new Gson();
        return gson.fromJson(
                jsonStr,cls);
    }

    public static <T> List<T> getList(String json, Class<T> cls) {
        List<T> list = new ArrayList<>();

        if (TextUtils.isEmpty(json)) {
            return  list;
        }

            try {
                JsonParser parser = new JsonParser();
                JsonArray jsonArray = parser.parse(json).getAsJsonArray();
                Gson gson = new Gson();

                for (int index = 0; index < jsonArray.size(); index++) {
                    JsonElement element = jsonArray.get(index);
                    T t = gson.fromJson(element, cls);
                    list.add(t);
                }
                return list;


            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return list;
            }





    }
    public static String toJson(Object object) {
        return new Gson().toJson(object);
    }


}
